package com.itheima.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.constant.TokenConstant;
import com.itheima.pojo.Employee;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 小帅蓝
 * @Date 2022/6/18 10:33
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private RedisTemplate<Object, Object> redis;

    public LoginInterceptor() {

    }

    public LoginInterceptor(RedisTemplate<Object, Object> redisTemplate) {
        this.redis = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.通过request获取前端传送过来的token
        request.setCharacterEncoding("UTF-8");
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(token)) {
            //2 token不为空
            //2.1根据token，从redis中获取用户信息（value）
            Object o = redis.opsForValue().get(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);
            //2.2 判断value，不为空，将用户信息的id存入TheadLocal，放行
            if (ObjectUtil.isNotNull(o)) {

                Employee employee = JSON.parseObject((String) o, Employee.class);
                if (ObjectUtil.isNotNull(employee)) {
                    TokenHolder.setCurrentId(employee.getId());
                    return true;
                }
            }
        }

        //通过response返回失败结果，拦截
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
